<?php

namespace app\company\controller;

use app\common\exception\BaseException;
use app\common\model\Store;
use app\common\model\Region1 as RegionModel;
use app\common\controller\CompanyController;
use app\common\model\RegionStore;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\common\service\GeocodeService;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="片区管理")
 */
class Region extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new RegionModel();
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->sceneValidate($post, 'add');
        $post['company_id'] = $this->companyId;

        try {
            $this->model->transaction(function () use ($post)
            {
                $config = geocodeConfig();
                if (!$config) throw new BaseException(['message' => '暂无配置,请联系管理员']);
                $allowType   = $config['allow_type'];
                $local       = GeocodeService::instance()->setConfig($config)->$allowType($post['name']);
                $post['lon'] = $local['lon'];
                $post['lat'] = $local['lat'];
                $this->model->save($post);
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }


    /**
     * @NodeAnnotation(title="片区列表-片区未绑定")
     */
    public function store($id = 0): Json
    {
        if (!$id) return $this->error('参数错误');
        $sql = new Store();

        $bindStore = (new RegionStore())->where(['company_id' => $this->companyId, 'region_id' => $id])
                                        ->column('store_id');
        $list      = $sql->where(['company_id' => $this->companyId])
                         ->whereNotIn('id', $bindStore)
                         ->field('id,name,lon,lat')
                         ->select()->toArray();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="片区绑定门店")
     */
    public function bind(Request $request, $id = 0): Json
    {
        $this->checkPost();
        $storeIds = $request->post('store_id', '');
        if (!$storeIds) return $this->error('请选择门店');
        $storeIds = explode(',', $storeIds);
        // 过滤已经帮过的门店
        $storeIds = array_diff($storeIds,
                               (new RegionStore())->where(['company_id' => $this->companyId, 'salesman_id' => $id])
                                                  ->column('store_id'));
        try {
            $this->model->transaction(function () use ($id, $storeIds, &$save)
            {
                $data = array_map(function ($storeId) use ($id)
                {
                    return ['company_id' => $this->companyId, 'salesman_id' => $id, 'store_id' => $storeId];
                }, $storeIds);
                $save = (new RegionStore())->saveAll($data);
            });
        } catch (\Exception $e) {
            $this->error('保存失败');
        }
        if ($save) return $this->success('保存成功');
        return $this->error('保存失败');
    }
}